package cn.bone.ou.user.service.impl;

import cn.bone.base.annotation.MyLogger;
import cn.bone.base.auth.JWTInfo;
import cn.bone.base.bean.CommonResult;
import cn.bone.base.bean.DataGrid;
import cn.bone.base.bean.Ref;
import cn.bone.base.dict.Dict;
import cn.bone.base.utils.TimeUtil;
import cn.bone.ou.community.bean.House;
import cn.bone.ou.community.mapper.HouseMapper;
import cn.bone.ou.user.bean.User;
import cn.bone.ou.user.bean.UserApply;
import cn.bone.ou.user.dto.UserApplyDto;
import cn.bone.ou.user.mapper.UserApplyMapper;
import cn.bone.ou.user.mapper.UserMapper;
import cn.bone.ou.user.param.ApplyParam;
import cn.bone.ou.user.service.IUserApplyService;
import cn.bone.ou.user.vo.UserApplyVo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Transactional
public class UserApplyServiceImpl implements IUserApplyService {

    @Resource
    private UserApplyMapper applyMapper;
    @Resource
    private UserMapper userMapper;
    @Resource
    private HouseMapper houseMapper;

    /**申请通过*/
    @MyLogger(msg = "接受用户申请")
    public CommonResult accept(ApplyParam.AcceptParam param){
        UserApply apply = applyMapper.selectById(param.getApplyId());
        if (apply==null){
            return Ref.error("错误的申请编号");
        }
        if(apply.getApplyState()==1){
            return Ref.error("该申请已通过");
        }
        if(apply.getApplyState()==2){
            return Ref.error("该申请已被驳回");
        }
        User user = userMapper.selectById(apply.getUserId());
        if(user==null){
            return Ref.error("数据错误");
        }
        if(user.getUsable()==0){
            return Ref.error("用户已被禁用");
        }

        //住户申请
        if(apply.getApplyType()==1){
            //判断用户类型是否是游客
            if(user.getUserType().intValue()==Dict.UserType.zhuhu){
                return Ref.error("该用户已经是住户，请驳回申请");
            }
            if(user.getUserType().intValue()==Dict.UserType.yezhu){
                return Ref.error("该用户已经是业主，请驳回申请");
            }

            //住户申请时,判断手机号在本小区是否存在
            User temp = userMapper.getByPhoneNumAndCommunityId(apply.getCommunityId(), apply.getPhoneNum());
            if(temp!=null){
                return Ref.error("该手机号已在本小区被使用");
            }

            user.setUserType(2);
            user.setHouseId(apply.getHouseId());
            user.setPhoneNum(apply.getPhoneNum());
        }else if(apply.getApplyType()==2){
            if(user.getUserType().intValue()==Dict.UserType.youke){
                return Ref.error("该用户为游客，不能申请成为业主");
            }
            if(user.getUserType().intValue()==Dict.UserType.yezhu){
                return Ref.error("该用户已经是业主，请驳回申请");
            }
            user.setUserType(3);
            user.setGender(apply.getGender());
            user.setRealName(apply.getRealName());
            user.setIdCard(apply.getIdCard());
            user.setIdCardFront(apply.getIdCardFront());
            user.setIdCardBack(apply.getIdCardBack());

            //业主申请通过后,房屋状态改成已认证
            House house = houseMapper.selectById(user.getHouseId());
            house.setIsAuth(1);
            houseMapper.updateById(house);
        }
        userMapper.updateById(user);

        JWTInfo jwtInfo = JWTInfo.get();
        apply.setApplyState(1);
        apply.setVerifyUserId(jwtInfo.getUserId());
        apply.setVerifyTime(new Date());
        applyMapper.updateById(apply);
        return Ref.ok();
    }

    /**申请不通过*/
    @MyLogger(msg = "拒绝用户申请")
    public CommonResult refuse(ApplyParam.RefuseParam param){
        UserApply apply = applyMapper.selectById(param.getApplyId());
        if (apply==null){
            return Ref.error("错误的申请编号");
        }
        if(apply.getApplyState()==1){
            return Ref.error("该申请已通过");
        }
        if(apply.getApplyState()==2){
            return Ref.error("该申请已被驳回");
        }
        JWTInfo jwtInfo = JWTInfo.get();
        apply.setApplyState(2);
        apply.setVerifyUserId(jwtInfo.getUserId());
        apply.setVerifyTime(new Date());
        applyMapper.updateById(apply);
        return Ref.ok();
    }

    /**申请列表*/
    public CommonResult<DataGrid<UserApplyVo.ListVo>> list(ApplyParam.ListParam param){
        List<UserApplyDto.ListDto> dtos = applyMapper.list(param.getCommunityId(),
                param.getStart(), param.getNum(),
                param.getApplyState(), param.getApplyType());
        int count = applyMapper.countList(param.getCommunityId(),
                param.getApplyState(),param.getApplyType());

        List<UserApplyVo.ListVo> vos = dtos.stream().map(dto->{
            UserApplyVo.ListVo vo = new UserApplyVo.ListVo();
            vo.setApplyId(dto.getId());
            vo.setApplyType(dto.getApplyType());
            vo.setApplyState(dto.getApplyState());
            vo.setPhoneNum(dto.getPhoneNum());
            vo.setRealName(dto.getRealName());
            vo.setIdCard(dto.getIdCard());
            vo.setGender(dto.getGender());
            vo.setIdCardFront(dto.getIdCardFront());
            vo.setIdCardBack(dto.getIdCardBack());
            vo.setCreateTime(dto.getCreateTime()==null?"": TimeUtil.formaterYYYYMMddHHmm(dto.getCreateTime()));
            vo.setVerifyTime(dto.getVerifyName()==null?"": TimeUtil.formaterYYYYMMddHHmm(dto.getVerifyTime()));
            vo.setNickName(dto.getNickName());
            vo.setBuildNum(dto.getBuildNum());
            vo.setUnitNum(dto.getUnitNum());
            vo.setHouseNum(dto.getHouseNum());
            vo.setVerifyName(dto.getVerifyName());
            return vo;
        }).collect(Collectors.toList());

        DataGrid<UserApplyVo.ListVo> dataGrid = new DataGrid<>();
        dataGrid.setTotal(count);
        dataGrid.setRows(vos);
        return Ref.ok(dataGrid);
    }
}
